﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// 封装抽屉数据，由父对象和抽屉list构成
/// </summary>
public class PoolData
{
    //抽屉中物体的父对象
    public GameObject fatherObj;
    //对象容器
    public List<GameObject> poolList;
    /// <summary>
    /// 初始化这个容器
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="poolObj"></param>
    public PoolData(GameObject obj,GameObject poolObj)
    {
        fatherObj = new GameObject(obj.name);
        fatherObj.transform.parent = poolObj.transform;
        poolList = new List<GameObject>() { };
        PushObj(obj);
    }
    /// <summary>
    /// 往抽屉里面放东西
    /// </summary>
    /// <param name="obj"></param>
    public void PushObj(GameObject obj)
    {
        obj.SetActive(false);
        poolList.Add(obj);
        obj.transform.parent = fatherObj.transform;
    }
    /// <summary>
    /// 从抽屉里面取东西
    /// </summary>
    /// <returns></returns>
    public GameObject GetObj()
    {
        GameObject obj = null;
        obj = poolList[0];
        poolList.RemoveAt(0);
        obj.SetActive(true);
        obj.transform.parent = null;
        return obj;
    }


}

public class PoolManager : BaseManager<PoolManager>
{
    public Dictionary<string, PoolData> poolDic = new Dictionary<string, PoolData>();

    private GameObject poolObj;
    //拿东西
    public void GetObj(string name, UnityAction<GameObject> callback)
    {
        //如果存在抽屉list且里面有东西
        if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
        {
           callback(poolDic[name].GetObj());
        }
        else 
        {
            ResourceMgr.GetInstance().LoadAsync<GameObject>(name,(o)=> { o.name = name;callback(o); });
            //obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
        }
        //把拿出来这个物体名字改成和name值一样，方便再找名字放回去
        //obj.name = name;
        
    }
    //放东西
    public void PushObj(string name,GameObject obj)
    {
        
        if (poolObj == null)
        {
            poolObj = new GameObject("pool");
        }
        obj.transform.parent = poolObj.transform;

        
        //如果有抽屉list,就直接放进去抽屉list
        if (poolDic.ContainsKey(name))
        {
            poolDic[name].PushObj(obj);
        }
        else 
        {
            poolDic.Add(name, new PoolData(obj,poolObj));          
        }
    }

    public void Clear()
    {
        poolDic.Clear();
        poolObj = null;
    }
}
